package org.cmind.soap.android;

import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import android.util.Log;

public class SoapRequest {

    private final DefaultHttpClient httpClient;

    /**
     * 
     * @param url
     *            Endpoint url
     * @param soapAction
     * 
     * @param envelope
     * @param rh
     * @see org.cmind.soap.android.response.SimpleResponseHandler
     * 
     */
    public void callWebService(String url, String soapAction, SoapObject envelope, ResponseHandler<String> rh) {
        SoapToXml stx = new SoapToXml();
        callWebService(url, soapAction, stx.produceXml(envelope), rh);
    }

    public SoapRequest() {
        httpClient = new DefaultHttpClient();
    }

    public SoapRequest(DefaultHttpClient client) {
        httpClient = client;
    }

    private String callWebService(String url, String soapAction, String envelope, ResponseHandler<String> rh) {

        // request parameters
        HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 15000);
        // set parameter
        HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

        // POST the envelope
        HttpPost httppost = new HttpPost(url);

        // add headers
        httppost.setHeader("soapaction", soapAction);
        httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

        String responseString = "";
        try {

            // the entity holds the request
            HttpEntity entity = new StringEntity(envelope);
            httppost.setEntity(entity);

            // Response handler

            responseString = httpClient.execute(httppost, rh);

        } catch (Exception e) {
            Log.v("exception", e.toString());
        }

        // close the connection
        httpClient.getConnectionManager().shutdown();
        return responseString;

    }

}
